package com.emapp.lccode.activity

import android.os.Bundle
import android.view.View
import androidx.lifecycle.viewModelScope
import com.emapp.lccode.R
import com.emapp.lccode.adapter.OrderImageKtAdapter
import com.emapp.lccode.base.BaseActivity1
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.base.EventBusConfig
import com.emapp.lccode.base.EventBusModel
import com.emapp.lccode.bean.OrderKt
import com.emapp.lccode.bean.SelectType
import com.emapp.lccode.databinding.ActivityOrderInforBinding
import com.emapp.lccode.mode.OrderKtViewModel
import com.emapp.lccode.utils.DividerOrientation
import com.emapp.lccode.utils.GlideEngine
import com.emapp.lccode.utils.divider
import com.emapp.lccode.utils.getColorExt
import com.emapp.lccode.utils.grid
import com.emapp.lccode.utils.setOnclickNoRepeat
import com.emapp.lccode.utils.toast
import com.emapp.lccode.view.PersonDialog
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.Toaster
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.style.PictureSelectorStyle
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.parseState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 我的工单详情-派单
 */
class OrderPaiInforKtActivity : BaseActivity1<OrderKtViewModel, ActivityOrderInforBinding>(),
    PersonDialog.SelectPersonListener {
    var id = ""
    var approve_type = ""
    var targetId = ""
    private val imageAdapter: OrderImageKtAdapter by lazy { OrderImageKtAdapter() }
    var images: ArrayList<LocalMedia> = arrayListOf()
    val personDialog: PersonDialog by lazy { PersonDialog() }
    var selectType: SelectType = SelectType()
    override fun initView(savedInstanceState: Bundle?) {
        immersionBar {
            titleBar(mViewBind.lvTitle.ivBar)
            statusBarDarkFont(true)
            fullScreen(true)
            statusBarColor(R.color.transparent)
            navigationBarColor(R.color.white)
        }
        mViewBind.lvTitle.tvTitle.text = "详情"
        mViewBind.lvTitle.tvRight.visibility = View.GONE
        mViewBind.btCancel.visibility = View.GONE//暂无接口
        EventBus.getDefault().register(this)
        id = intent.extras?.getString("id", "") ?: ""
        // var o=  intent.extras?.getParcelable("order")?: null

        approve_type = intent.extras?.getString("approve_type", "1") ?: "1"
        mViewBind.rvList.run {
            grid(4)
            adapter = imageAdapter
            divider {
                orientation = DividerOrientation.HORIZONTAL
                includeVisible = true
                setDivider(10, true)
                setColor(getColorExt(R.color.white))
            }
        }
        imageAdapter.run {
            setOnItemClickListener { adapter, view, position ->
                PictureSelector.create(this@OrderPaiInforKtActivity)
                    .openPreview()
                    .setImageEngine(GlideEngine.createGlideEngine())
                    .setSelectorUIStyle(PictureSelectorStyle())
                    .isPreviewFullScreenMode(true)
                    .isHidePreviewDownload(true) //.setExternalPreviewEventListener(new MyExternalPreviewEventListener(adapter))
                    .startActivityPreview(position, false, images)
            }
        }
        mViewBind.rgType.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rb_1 -> {
                    mViewBind.lvZhipai.visibility = (View.GONE)
                }

                R.id.rb_2 -> {
                    mViewBind.lvZhipai.visibility = (View.VISIBLE)
                }
            }
        }
        mViewModel.getOrderInfor(id)
    }

    override fun createObserver() {
        mViewModel.run {
            orderInfor.observe(this@OrderPaiInforKtActivity) { result ->
                parseState(result, {
                    setInfor(it[0])
                }, {
                    Toaster.show(it.errorMsg)
                })

            }
            paidan.observe(this@OrderPaiInforKtActivity) { result ->
                parseState(result, {
                    Toaster.show("提交成功")
                    EventBus.getDefault().post(EventBusModel(EventBusConfig.REFRESH_ORDER))
                    viewModelScope.launch {
                        delay(500)
                        finish()
                    }
                }, {
                    Toaster.show(it.errorMsg)
                })

            }
        }
    }

    private fun setInfor(infor: OrderKt) {
        mViewBind.tvName.text = infor.name
        mViewBind.tvNumber.text = infor.num_code
        mViewBind.tvAddress.text = infor.address
        mViewBind.tvContent.text = infor.content
        mViewBind.tvRemark.text = infor.remark
        if (infor.fileArray != null) {
            images.clear()
            infor.fileArray.forEach {
                var l = LocalMedia()
                l.path = BaseConfig.ROOT_URL + it.filepath
                images.add(l)
            }
            imageAdapter.submitList(images)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onBindViewClick() {
        setOnclickNoRepeat(
            mViewBind.lvTitle.ivLeft,
            mViewBind.lvTitle.tvRight,
            mViewBind.tvTarget,
            mViewBind.btOk
        ) {
            when (it.id) {
                R.id.iv_left -> {
                    finish()
                }

                R.id.tv_target -> {
                    personDialog.listener = this
                    personDialog.selectType = selectType
                    personDialog.show(this)
                }

                R.id.bt_ok -> {
                    var check = if (mViewBind.rb1.isChecked) "2" else "1"
                    var check_node = if (mViewBind.rb1.isChecked) "1" else "2"
                    if (mViewBind.tvTarget.text.toString().isEmpty()) {
                        "请选择指派人员".toast()
                        return@setOnclickNoRepeat
                    }
                    mViewModel.paidan(check, id, targetId, check_node, approve_type)
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(event: EventBusModel) {
        when (event.type) {
            EventBusConfig.FINISH -> {
            }

            else -> {}
        }
    }

    override fun onSelectPersonComplete(type: SelectType) {
        selectType = type
        targetId = type.id1
        mViewBind.tvTarget.text = type.name1
    }

}
